<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
    <title>drag</title>
    <style>
      .draggable {
        width: 100px;
        height: 100px;
        background-color: lightcoral;
        position: absolute;
        cursor: move;
      }
    </style>
  </head>
  <body>
    <div class="draggable"></div>

    <script>
        let draggable = document.querySelector('.draggable');
        //先定义2个变量，记录原始的鼠标相对于拖动元素左边界和上边界的偏移量
        let offsetX=0,offsetY=0;
        //定义一个标志 ，表示当前是否正在拖动中
        let dragging=false;
        draggable.addEventListener('mousedown',(event)=>{
            dragging=true;
            //计算鼠标的位置相对于拖动元素左边界和上边界的偏移量
            //让鼠标距离视口左端的距离减去拖动元素距离视口左端的距离
            offsetX=event.clientX-draggable.offsetLeft;
            offsetY=event.clientY-draggable.offsetTop;
        });
        draggable.addEventListener('mousemove',(event)=>{
            if(dragging){
                //先计算新的位置 用最新的鼠标的位置减去初始的偏移量
                const newX = event.clientX-offsetX;
                const newY = event.clientY-offsetY;
                //计算left和top值的最大值
                //left最大值等于视口的宽度减去拖动的元素的宽度
                const maxLeft = document.documentElement.clientWidth-draggable.offsetWidth;
                //top最大值等于视口的高度减去拖动的元素的高度
                const maxTop = document.documentElement.clientHeight-draggable.offsetHeight;
                //规定X大于等于0，小于等于最大值
                const clampedX = Math.max(0,Math.min(newX,maxLeft));
                 //规定Y大于等于0，小于等于最大值
                const clampedY = Math.max(0,Math.min(newY,maxTop));
                draggable.style.left = clampedX+'px';
                draggable.style.top = clampedY+'px';
            }
        });
        draggable.addEventListener('mouseup',(event)=>{
            dragging=false;
        });
    </script>
  </body>
</html>
